<template>
	<div class="app-container">
		<!--工具栏-->
		<div class="head-container">
			<div v-if="crud.props.searchToggle">
				<!-- 搜索 -->
				<el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item"
					@keyup.enter.native="crud.toQuery" />
				<el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
					<el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name"
						:value="item.key" />
				</el-select>
				<rrOperation :crud="crud" />
			</div>
			<!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
			<crudOperation :permission="permission" />
			<!--表单组件-->
			<el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
				:title="crud.status.title" width="60%">
				<el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
					<el-form-item label="招商名称" prop="businessName">
						<el-input v-model="form.businessName" style="width: 330px;" />
					</el-form-item>
					<el-form-item label="商户类型">
						<el-select @change="handleChange(type)" style="width: 330px;" v-model="type" filterable placeholder="请选择">
							<el-option v-for="item in businessType" :key="item.value" :label="item.label"
								:value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="资质图片" style="display: block;">
						<MaterialList v-model="aptitudeUrlArr" style="width: 330px;" type="image" :num="1" :width="150"
							:height="150" />
					</el-form-item>
					<el-form-item label="资质名称" prop="aptitudeName">
						<el-input disabled v-model="form.aptitudeName" style="width: 280px;" />
					</el-form-item>
					<el-form-item label="资质税号" prop="aptitudeTaxNo">
						<el-input disabled v-model="form.aptitudeTaxNo" style="width: 280px;" />
					</el-form-item>
					<el-button class="btn" type="primary" @click="getImgMsg('0' ,aptitudeUrlArr)">一键获取</el-button>
					<el-form-item label="身份证正">
						<MaterialList v-model="obverseUrlArr" style="width: 330px;" type="image" :num="1" :width="150"
							:height="150" />
					</el-form-item>
					<el-form-item label="身份证反">
						<MaterialList v-model="reverseUrlArr" style="width: 330px;" type="image" :num="1" :width="150"
							:height="150" />
					</el-form-item>
					<el-form-item label="真实姓名">
						<el-input disabled v-model="form.realName" style="width: 280px;" />
					</el-form-item>
					<el-form-item label="身份证号">
						<el-input disabled v-model="form.cardId" style="width: 280px;" />
					</el-form-item>
					<el-button class="btn" type="primary" @click="getImgMsg('1', obverseUrlArr)">一键获取</el-button>
					<el-form-item label="手机号">
						<el-input v-model="form.realPhone" style="width: 280px;" />
					</el-form-item>
					<el-form-item label="状态" prop="status">
						<el-radio-group v-model="form.status" style="width: 280px;">
							<el-radio :label="1">正常</el-radio>
							<el-radio :label="0">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="寄存合同模板" style="display: block;">
						<a :href="`${imgUrl}/cloud/file/deposit.doc`">寄存合同模板<span class="blue">下载</span></a>
						<el-upload
						  style="margin-left: 160px;display: inline"	
						  :action="uploadApi"
						  :headers="headers"
						  :file-list="depositFileList"
						  :on-progress="handleProgress"
						  :before-upload="beforeUpload"
						  :on-success=" 
							(response, file, fileList) => {
							  return handleSuccess(response, file, fileList, 0);
						  }"
						  :data="{type: 1}"
						  :limit="1"
						>
						  <el-button class="btn" size="small" type="primary">上传</el-button>
						</el-upload>
					</el-form-item>
					<el-form-item label="回收合同模板" style="display: block;">
						<a :href="`${imgUrl}/cloud/file/recovery.doc`">回收合同模板<span class="blue">下载</span></a>
						<el-upload
						  style="margin-left: 160px;display: inline"	
						  :action="uploadApi"
						  :headers="headers"
						  :file-list="recoveryFileList"
						  :on-progress="handleProgress"
						  :before-upload="beforeUpload"
						  :on-success="
							(response, file, fileList) => {
							  return handleSuccess(response, file, fileList, 1);
						  }"
						  :data="{type: 1}"
						  :limit="1"
						>
						  <el-button class="btn" size="small" type="primary">上传</el-button>
						</el-upload>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button type="text" @click="crud.cancelCU">取消</el-button>
					<el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
				</div>
			</el-dialog>
			<!--表格渲染-->
			<el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
				@selection-change="crud.selectionChangeHandler">
				<el-table-column type="selection" width="55" />
				<el-table-column v-if="columns.visible('businessName')" prop="businessName" label="招商名称" />
				<el-table-column v-if="columns.visible('aptitudeName')" prop="aptitudeName" label="资质名称" show-overflow-tooltip/>
				<el-table-column v-if="columns.visible('aptitudeTaxNo')" prop="aptitudeTaxNo"
					label="资质税号" />
				<el-table-column v-if="columns.visible('businessType')" prop="businessType" label="商户类型">
					<template slot-scope="scope">
						{{ scope.row.businessType === 0 ? '企业' : scope.row.businessType === 1 ? '个体商户' : '其他' }}
					</template>
				</el-table-column>
				<el-table-column v-if="columns.visible('aptitudeUrl')" prop="aptitudeUrl" label="资质图片">
					<template slot-scope="scope">
						<a :href="scope.row.aptitudeUrl" style="color: #42b983" target="_blank">
							<img :src="scope.row.aptitudeUrl" alt="点击打开" class="table-img" />
						</a>
					</template>
				</el-table-column>
				<el-table-column v-if="columns.visible('realPhone')" prop="realPhone" label="手机号" show-overflow-tooltip/>
				<el-table-column v-if="columns.visible('realName')" prop="realName" label="真实姓名" />
				<el-table-column v-if="columns.visible('cardId')" prop="cardId" label="身份证号码" show-overflow-tooltip/>
				<el-table-column v-if="columns.visible('obverseUrl')" prop="obverseUrl" label="身份证正">
					<template slot-scope="scope">
						<a :href="scope.row.obverseUrl" style="color: #42b983" target="_blank">
							<img :src="scope.row.obverseUrl" alt="点击打开" class="table-img" />
						</a>
					</template>
				</el-table-column>
				<el-table-column v-if="columns.visible('reverseUrl')" prop="reverseUrl" label="身份证反">
					<template slot-scope="scope">
						<a :href="scope.row.reverseUrl" style="color: #42b983" target="_blank">
							<img :src="scope.row.reverseUrl" alt="点击打开" class="table-img" />
						</a>
					</template>
				</el-table-column>
				<el-table-column v-if="columns.visible('status')" prop="status" label="状态">
					<template slot-scope="scope">
						{{ scope.row.status === 1 ? '正常' : '禁用' }}
					</template>
				</el-table-column>
				<el-table-column v-if="columns.visible('createTime')" prop="createTime" label="添加时间" show-overflow-tooltip>
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.createTime) }}</span>
					</template>
				</el-table-column>
				<el-table-column v-if="columns.visible('updateTime')" prop="updateTime" label="修改时间" show-overflow-tooltip>
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.updateTime) }}</span>
					</template>
				</el-table-column>
				<el-table-column v-permission="['admin','syBusinessJoin:edit','syBusinessJoin:del']" label="操作"
					width="150px" align="center">
					<template slot-scope="scope">
						<udOperation :data="scope.row" :permission="permission" />
					</template>
				</el-table-column>
			</el-table>
			<!--分页组件-->
			<pagination />
		</div>
	</div>
</template>

<script>
	import crudSyBusinessJoin from '@/api/syBusinessJoin'
	import {getImageInfo} from '@/api/syBusinessJoin'
	import CRUD, {
		presenter,
		header,
		form,
		crud
	} from '@crud/crud'
	import rrOperation from '@crud/RR.operation'
	import crudOperation from '@crud/CRUD.operation'
	import udOperation from '@crud/UD.operation'
	import pagination from '@crud/Pagination'
	import MaterialList from "@/components/material";
	import { getToken } from '@/utils/auth'
	import { mapGetters } from 'vuex'
	import { addObj } from '@/api/tools/material'

	// crud交由presenter持有
	const defaultCrud = CRUD({
		title: '',
		url: 'api/syBusinessJoin',
		sort: 'id,desc',
		crudMethod: {
			...crudSyBusinessJoin
		}
	})
	const defaultForm = {
		id: null,
		businessName: null,
		aptitudeName: null,
		aptitudeTaxNo: null,
		businessType: null,
		aptitudeUrl: null,
		realPhone: null,
		realName: null,
		cardId: null,
		obverseUrl: null,
		reverseUrl: null,
		status: 1,
		createTime: null,
		updateTime: null,
		contractTempJc: null,
		contractTempHs: null,
	}
	export default {
		name: 'SyBusinessJoin',
		components: {
			pagination,
			crudOperation,
			rrOperation,
			udOperation,
			MaterialList
		},
		mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
		dicts: ['is_enable', 'business_type'],
		data() {
			return {
				aptitudeUrlArr: [],
				obverseUrlArr: [],
				reverseUrlArr: [],
				permission: {
					add: ['admin', 'syBusinessJoin:add'],
					edit: ['admin', 'syBusinessJoin:edit'],
					del: ['admin', 'syBusinessJoin:del']
				},
				rules: {
					businessName: [{
						required: true,
						message: '招商名称不能为空',
						trigger: 'blur'
					}],
					aptitudeName: [{
						required: true,
						message: '资质名称(企业名称/个体商户名称)不能为空',
						trigger: 'blur'
					}],
					status: [{
						required: true,
						message: '状态（1：正常 0：禁用）不能为空',
						trigger: 'blur'
					}],
					createTime: [{
						required: true,
						message: '添加时间不能为空',
						trigger: 'blur'
					}]
				},
				queryTypeOptions: [{
						key: 'businessName',
						display_name: '招商名称'
					},
					{
						key: 'realPhone',
						display_name: '认证人手机号'
					}
				],
				businessType: [{
						lable: 0,
						value: '企业'
					},
					{
						lable: 1,
						value: '个体商户'
					},
					{
						lable: 2,
						value: '其它'
					},
				],
				type: '',
				headers: {
				  Authorization: getToken()
				},
				groupId: null,
				imgUrl: '',
				depositFileList: [],
				recoveryFileList: []
			}
		},
		watch: {
			"aptitudeUrlArr": function(val) {
				if (val) {
					this.form.aptitudeUrl = val.join(",");
				}
			},
			"obverseUrlArr": function(val) {
				if (val) {
					this.form.obverseUrl = val.join(",");
				}
			},
			"reverseUrlArr": function(val) {
				if (val) {
					this.form.reverseUrl = val.join(",");
				}
			},
		},
		computed: {
		  ...mapGetters([
		    'uploadApi'
		  ])
		},
		created() {
			this.imgUrl = process.env.VUE_APP_IMG_API
		},
		methods: {
			// 获取数据前设置好接口地址
			[CRUD.HOOK.beforeRefresh]() {
				const query = this.query
				if (query.type && query.value) {
					this.crud.params[query.type] = query.value
				} else {
					delete this.crud.params.businessName
					delete this.crud.params.realPhone
				}
				return true
			}, 
			// 新增与编辑前做的操作
			[CRUD.HOOK.afterToCU](crud, form) {
				this.depositFileList = []
				this.recoveryFileList = []
				if (crud.status.title === '编辑') {
					this.depositFileList = [{name: form.contractTempJc}]
					this.recoveryFileList = [{name: form.contractTempHs}]
				}
				if (!form.id) {
					this.type = ''
				} else {
					if (form.businessType == 0) {
						this.type = '企业'
					} else if (form.businessType == 1) {
						this.type = '个体商户'
					} else {
						this.type = '其他'
					}
				}
				if (form.aptitudeUrl && form.id) {
					this.aptitudeUrlArr = form.aptitudeUrl.split(",");
				} else {
					this.aptitudeUrlArr = []
				}
				if (form.obverseUrl && form.id) {
					this.obverseUrlArr = form.obverseUrl.split(",");
				} else {
					this.obverseUrlArr = []
				}
				if (form.reverseUrl && form.id) {
					this.reverseUrlArr = form.reverseUrl.split(",");
				} else {
					this.reverseUrlArr = []
				}
			},
			handleChange(type) {
				if (type === '企业') {
					this.form.businessType = 0
				} else if (type === '个体商户') {
					this.form.businessType = 1
				} else {
					this.form.businessType = 2
				}
			},
			getImgMsg(type, url) {
				let data = {
					jsonData: {
						type: type,
						imageUrl: url[0]
					}
				}
				getImageInfo(data).then(res => {
					let data = JSON.parse(res.data)
					if (type === '0') {
						this.form.aptitudeName = data.aptitudeName
						this.form.aptitudeTaxNo = data.aptitudeTaxNo
					} else if (type === '1') {
						this.form.realName = data.realName
						this.form.cardId = data.cardId
					}
				})
			},
			handleProgress(event, file, fileList) {},
			handleSuccess(response, file, fileList, type) {
			  const that = this
			  this.uploadProgress = 0
			  addObj({
			    type: '1',
			    groupId: this.groupId != '-1' ? this.groupId : null,
			    name: file.name,
			    url: response.link
			  }).then(() => {
				if (type === 0) {
					this.form.contractTempJc = response.link
					this.depositFileList = [file];
				} else {
					this.form.contractTempHs = response.link
					this.recoveryFileList = [file];
				}
			  })
			  
			},
			beforeUpload(file) {
			  const isFTL = /\.ftl$/.test(file.name);
			  if (!isFTL) {
			  	this.$message.error('只能上传.ftl格式的文件！');
			  	return false
			  }
			  const isLt2M = file.size / 1024 / 1024 < 2
			  if (!isLt2M) {
			    this.$message.error('上传合同大小不能超过 2MB!')
			  }
			  return isFTL && isLt2M
			},
		}
	}
</script>

<style scoped>
	.table-img {
		display: inline-block;
		text-align: center;
		background: #ccc;
		color: #fff;
		white-space: nowrap;
		position: relative;
		overflow: hidden;
		vertical-align: middle;
		width: 32px;
		height: 32px;
		line-height: 32px;
	}

	.el-form-item {
		display: inline-block;
	}
	
	.btn {
		margin-left: 20px;
	}
	
	.blue {
		color: blue;
		margin-left: 10px;
		text-decoration: underline;
	}
</style>